package com.szcinda.service.dto.coach;

import com.szcinda.repository.Coach;
import com.szcinda.repository.CoachRepository;
import com.szcinda.service.SnowFlakeFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.Assert;

import java.util.List;

@Service
@Transactional
public class CoachServiceImpl implements CoachService {
    private final CoachRepository coachRepository;
    private final SnowFlakeFactory snowFlakeFactory;

    public CoachServiceImpl(CoachRepository coachRepository) {
        this.coachRepository = coachRepository;
        this.snowFlakeFactory = SnowFlakeFactory.getInstance();
    }

    @Override
    public void create(CreateCoachDto createBGTypeDto) {
        Coach coach = coachRepository.findByName(createBGTypeDto.getName());
        Assert.isTrue(coach == null, "存在相同出境口岸的记录");
        coach = new Coach();
        BeanUtils.copyProperties(createBGTypeDto, coach);
        coach.setId(snowFlakeFactory.nextId("CO"));
        coachRepository.save(coach);
    }

    @Override
    public void delete(String id, String userId) {
        coachRepository.delete(id);
    }

    @Override
    public List<Coach> findAll() {
        return coachRepository.findAll();
    }

    @Override
    public void batchCreate(List<CoachImportDto> importDatas, String opId) {
        List<Coach> coaches = coachRepository.findAll();
        for (CoachImportDto importDto : importDatas) {
            boolean b = coaches.stream().noneMatch(coach -> coach.getName().equals(importDto.getName()));
            if (b) {
                Coach coach = new Coach();
                BeanUtils.copyProperties(importDto, coach);
                coach.setId(snowFlakeFactory.nextId("CO"));
                coachRepository.save(coach);
            }
        }
    }
}
